using System;
using System.Runtime.InteropServices;

namespace winsw
{
	internal class ServiceManager : IDisposable
	{
		private IntPtr Handle;

		public ServiceManager()
		{
			Handle = Advapi32.OpenSCManager(null, null, 983103u);
			if (Handle == IntPtr.Zero)
			{
				throw new Exception($"Error connecting to Service Control Manager. Error provided was: 0x{Marshal.GetLastWin32Error():X}");
			}
		}

		public Service Open(string serviceName)
		{
			IntPtr intPtr = Advapi32.OpenService(Handle, serviceName, 983551u);
			if (intPtr == IntPtr.Zero)
			{
				throw new Exception($"Error opening service for modifying. Error returned was: 0x{Marshal.GetLastWin32Error():X}");
			}
			return new Service(intPtr);
		}

		public void Dispose()
		{
			if (Handle != IntPtr.Zero)
			{
				Advapi32.CloseServiceHandle(Handle);
			}
			Handle = IntPtr.Zero;
		}
	}
}
